package com.attendance.controller;

import com.attendance.pojo.TaskUserLog;
import com.attendance.result.LayuiMiniPage;
import com.attendance.security.user.service.UserService;
import com.attendance.service.TaskRecordServiceImpl;
import com.attendance.service.TaskServiceImpl;
import com.attendance.web.Result;
import com.attendance.web.ResultCode;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Joiner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

/**
 * 任务记录控制器
 *
 * @author 今朝
 * @date 2021/03/24
 */
@Controller
@RequestMapping("/system/task/record/")
public class TaskRecordController {
    @Autowired
    TaskRecordServiceImpl taskRecordService;
    @Autowired
    UserService userService;
    @Autowired
    TaskServiceImpl taskService;

    @GetMapping()
    public String table() {
        return "/system/task/record/table";
    }

    @GetMapping("/add")
    public ModelAndView add() {
        ModelAndView modelAndView = new ModelAndView("/system/task/record/add");
        Long userId = userService.getUser().getUserId();
        List<Long> taskIdsById = taskService.getTaskIdsById(userId);
        modelAndView.addObject("userId",userId);
        modelAndView.addObject("taskIds", Joiner.on(",").join(taskIdsById));
        modelAndView.addObject("taskNames",Joiner.on(",").join(taskService.getTaskTitleByIds(taskIdsById)));
        return modelAndView;
    }

    @ResponseBody
    @GetMapping("/listPage")
    public LayuiMiniPage<TaskUserLog> getListPage(Integer page, Integer limit, String searchParams) {
        if (searchParams != null) {
            Page<TaskUserLog> listPage = taskRecordService.getListPage(page, limit, searchParams);
            return new LayuiMiniPage<>(200, "查询成功", listPage.getTotal(), listPage.getRecords());
        }
        Page<TaskUserLog> listPage = taskRecordService.getListPage(page, limit);
        return new LayuiMiniPage<>(200, "查询成功", listPage.getTotal(), listPage.getRecords());
    }

    @ResponseBody
    @PutMapping("/add")
    public Result add(TaskUserLog log,String taskIds) {
        try {
            if (taskRecordService.add(log, taskIds)) {
                return new Result(ResultCode.SUCCESS);
            } else {
                return new Result(ResultCode.FAIL);
            }
        } catch (Exception e) {
            return new Result(502,e.getMessage(),false);
        }
    }
}